package com.t2t.top.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;

import java.util.UUID;


public class AppCreate {

    private CuratorFramework client;

    /**
     * 函数入口
     *
     * @param args
     */
    public static void main(String[] args) {
        AppCreate bootStrap = new AppCreate();
        try {
            bootStrap.initialize();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化zookeeper
     */
    public void initialize() throws Exception {
        String connectionString = Constant.ZK_ADDRESS;
        int connectionTimeout = 5000;

        client = CuratorFrameworkFactory.newClient(Constant.ZK_ADDRESS, new RetryNTimes(3, connectionTimeout));
        client.start();
        System.out.println("zk client start successfully!");

        rootNodeChangeThread();
    }

    /**
     * 每20s改变一次 'root1'节点的数据
     */
    public void rootNodeChangeThread() throws Exception {
        if (client.checkExists().forPath(Constant.ZK_PATH_MONITOR) == null) {
            client.create().creatingParentsIfNeeded().forPath(Constant.ZK_PATH_MONITOR);
        }
        if (client.checkExists().forPath(Constant.ZK_PATH) != null) {
            client.delete().forPath(Constant.ZK_PATH);
        }
        while (true) {
            String uuidStr = UUID.randomUUID().toString();
            System.out.println(">>>>>>>>>> 产生随机的 uuid string,'uuidStr'===>" + uuidStr);
            if (client.checkExists().forPath(Constant.ZK_PATH) == null) {
                //PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, Constant.ZK_PATH, uuidStr.getBytes());
                //node.start();
                //node.waitForInitialCreate(3, TimeUnit.SECONDS);
                client.create().withMode(CreateMode.EPHEMERAL).forPath(Constant.ZK_PATH, uuidStr.getBytes());
            }

            client.setData().forPath(Constant.ZK_PATH, uuidStr.getBytes());

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                //ignore
            }
        }
    }
}